<template>
  <el-card shadow="never">
    <div slot="header" ref="topHeader">
      <el-form :inline="true" :model="listQuery">
        <el-form-item label="用户名:">
          <el-input style="width: 160px" v-model="listQuery.namePhone" placeholder="用户名/电话" clearable/>
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="listQuery.isEnable" style="width: 120px" placeholder="用户状态" clearable>
            <el-option label="启用" :value="true"/>
            <el-option label="已禁用" :value="false"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAddUser">增加</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" icon="el-icon-delete" @click="remove">删除</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <!--table data-->
      <el-table ref="tableCot" v-loading="loading" element-loading-text="请稍后..." :data="tableData" border style="width: 100%" :max-height="customTableHeight">
        <el-table-column type="selection" width="40"/>
        <el-table-column prop="userName" label="用户名" min-width="100" show-overflow-tooltip/>
        <el-table-column prop="nickName" label="昵称" min-width="100" show-overflow-tooltip/>
        <el-table-column prop="phone" label="电话" min-width="100" show-overflow-tooltip/>
        <el-table-column label="角色" min-width="150" show-overflow-tooltip>
          <template slot-scope="{row}">
            <el-tag style="margin-left: 2px;" v-for="(r, index) in row.roles" :key="index" size="mini">{{ r.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" min-width="100">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.isEnable?'已启用':'已禁用'" placement="top">
              <el-switch
                v-model="scope.row.isEnable"
                :active-value="true"
                :inactive-value="false"
                @change="switchChange(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="updateUser" label="创建人" min-width="100" show-overflow-tooltip/>
        <el-table-column prop="updateTime" label="最近更新时间" min-width="120"/>
        <el-table-column fixed="right" label="操作" width="126">
          <template slot-scope="scope">
            <el-tag style="cursor:pointer;margin-right: 4px;" size="mini" @click="handleEdit(scope)"><i class="el-icon-edit"/>编辑</el-tag>
            <el-tag style="cursor:pointer;" size="mini" type="danger" @click="remove(scope.row)"><i
              class="el-icon-delete"/>删除
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!--分頁-->
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList"/>

      <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'新增用户'">
        <el-form :model="role" label-width="80px" label-position="left">
            <el-form-item label="用户名称">
            <el-input v-model="role.userName" placeholder="请输入用户名称" />
            </el-form-item>
            <el-form-item label="用户昵称">
            <el-input v-model="role.phone" placeholder="请输入用户电话" />
            </el-form-item>
            <el-form-item label="用户电话">
            <el-input v-model="role.nickName" placeholder="请输入用户昵称" />
            </el-form-item>
            <el-form-item label="用户角色">
              <el-select v-model="value" multiple placeholder="请选择用户角色" style="width:100%;">
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
        </el-form>
        <div style="text-align:right;">
            <el-button type="default" @click="dialogVisible=false">
            {{ $t('permission.cancel') }}
            </el-button>
            <el-button type="primary" @click="confirmRole">
            {{ $t('permission.confirm') }}
            </el-button>
        </div>
    </el-dialog>

    </div>
  </el-card>
</template>
<script>
import Pagination from "@/components/Pagination";
// import systemUserApi from '@/api/system/user'

const defaultRole = {
  userName: "",
  nickName: "",
  phone: "",
  roles: [
    {
      id: 1,
      name: "超级管理员"
    },
    {
      id: 2,
      name: "管理员"
    }
  ],
}   

export default {
  name: "systemUser",
  components: { Pagination },
  data() {
    return {
      role: Object.assign({}, defaultRole),
      loading: false,
      dialogType: 'new',
      dialogVisible: false,
      customTableHeight: 200,
      formInline: {
        user: "",
        region: ""
      },
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 10,
        namePhone: null,
        isEnable: null
      },
      value: [],
      options: [
        {id: '1', 'name': '超级管理员'},
        {id: '2', 'name': '测试管理员'},
        {id: '3', 'name': '普通用户'},
        {id: '4', 'name': '管理员'}
      ],
      tableData: [
        {
          id: 1,
          userName: "wangwu",
          nickName: "王小虎",
          phone: "15565236541",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2020-11-23",
          updateTime: "2020-11-23"
        },
        {
          id: 2,
          userName: "zhangsan",
          nickName: "张三",
          phone: "70983928",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-12-11",
          updateTime: "2020-12-11"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        },
        {
          id: 2,
          userName: "lisi",
          nickName: "里斯",
          phone: "18895623548",
          roles: [
            {
              id: 1,
              name: "超级管理员"
            }
          ],
          isEnable: true,
          "createUser": "admin",
          "updateUser": "admin",
          createTime: "2019-05-02",
          updateTime: "2019-05-02"
        }
      ],
      addEditData: {}
    };
  },
  computed: {
    theme() {
      return this.$store.state.settings.theme;
    }
  },
  mounted() {
    this.getList();
    let that = this;
    window.onresize = () => {
      //37是box的header的padding，70=(60+10)是顶部的高度
      let tempHeaderHeight = this.$refs.topHeader.offsetHeight + 37 + 95;
      let tempHeight = document.body.clientHeight - (106 + tempHeaderHeight);
      if (tempHeight < 300) {
        tempHeight = 300;
      }
      that.customTableHeight = tempHeight;
    };
    setTimeout(function() {
      const resizeEvent = new Event("resize");
      window.dispatchEvent(resizeEvent);
    }, 100);
  },
  destroyed() {
    window.onresize = null;
  },
  methods: {
    handleFilter() {
      this.getList();
    },
    handleAddUser() {
      this.role = Object.assign({}, defaultRole)
      // if (this.$refs.tree) {
      //   this.$refs.tree.setCheckedNodes([])
      // }
      this.dialogType = 'new'
      this.dialogVisible = true

      // if (row) {
      //   row.role = [];
      //   if (row.roles) {
      //     row.roles.forEach(item => {
      //       row.role.push(item.roleId);
      //     });
      //   }
      //   this.addEditData = JSON.parse(JSON.stringify(row));
      // }
      // this.dialogVisible = true;
    },
    getList() {
      this.loading = true;
      // systemUserApi.list(this.listQuery).then(res => {
      //   this.tableData = res.data || []
      this.loading = false;
      // }).catch(() => this.loading = false)
    },
    switchChange(row) {
      const enable = row.isEnable;
      let text = "是否禁用该账户？";
      if (enable) {
        text = "确认启用该账户？";
      }
      this.$confirm(text, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnPressEscape: false,
        closeOnClickModal: false,
        type: "warning"
      })
        .then(() => {
          systemUserApi
            .status(row.id, enable)
            .then(res => {
              this.$message.success("操作成功");
            })
            .catch(() => {
              row.isEnable = !enable;
            });
        })
        .catch(() => {
          row.isEnable = !enable;
        });
    },
    addEdit(row) {
      // if (row) {
      //   row.role = [];
      //   if (row.roles) {
      //     row.roles.forEach(item => {
      //       row.role.push(item.roleId);
      //     });
      //   }
      //   this.addEditData = JSON.parse(JSON.stringify(row));
      // }
      // this.dialogVisible = true;
    },
    remove(row) {
      this.$confirm("删除后将无法恢复，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnPressEscape: false,
        closeOnClickModal: false,
        type: "warning"
      }).then(() => {
        systemUserApi.remove(row.id).then(res => {});
      });
    },
    closeDialog() {
      if (this.dialogVisible) {
        this.getList();
      }
      this.dialogVisible = false;
      this.addEditData = {
        id: null,
        username: "",
        nickName: "",
        phone: "",
        role: [],
        isEnable: true
      };
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      // this.checkStrictly = true
      // this.role = deepClone(scope.row)
      // this.$nextTick(() => {
      //   const routes = this.generateRoutes(this.role.routes)
      //   this.$refs.tree.setCheckedNodes(this.generateArr(routes))
      //   // set checked state of a node not affects its father and child nodes
      //   this.checkStrictly = false
      // })
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'

      const checkedKeys = this.$refs.tree.getCheckedKeys()
      this.role.routes = this.generateTree(deepClone(this.serviceRoutes), '/', checkedKeys)

      if (isEdit) {
        await updateRole(this.role.key, this.role)
        for (let index = 0; index < this.rolesList.length; index++) {
          if (this.rolesList[index].key === this.role.key) {
            this.rolesList.splice(index, 1, Object.assign({}, this.role))
            break
          }
        }
      } else {
        const { data } = await addRole(this.role)
        this.role.key = data.key
        this.rolesList.push(this.role)
      }

      const { description, key, name } = this.role
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: `
            <div>Role Key: ${key}</div>
            <div>Role Name: ${name}</div>
            <div>Description: ${description}</div>
          `,
        type: 'success'
      })
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ... parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
};
</script>
<style scoped lang="scss">
</style>
